package com.xm.ojbackendjudge.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.xm.ojbackendmodel.model.codesandbox.JudgeInfo;
import com.xm.ojbackendmodel.model.dto.question.JudgeCase;
import com.xm.ojbackendmodel.model.dto.question.JudgeConfig;
import com.xm.ojbackendmodel.model.entity.Question;
import com.xm.ojbackendmodel.model.enums.JudgeInfoMessageEnum;

import java.util.List;

public class DefaultJudgeStrategy implements JudgeStrategy{
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {

        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        Long memory = judgeInfo.getMemory();
        Long time = judgeInfo.getTime();

        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        Question question = judgeContext.getQuestion();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        //返回结果
        JudgeInfoMessageEnum resultStatus = JudgeInfoMessageEnum.ACCEPTED;
        JudgeInfo judgeInfoResponse = new JudgeInfo();
        judgeInfoResponse.setTime(time);
        judgeInfoResponse.setMemory(memory);
        //输出样例数量不匹配
        if (outputList.size() != inputList.size()) {
            resultStatus = JudgeInfoMessageEnum.WRONG_ANSWER;
            judgeInfoResponse.setMessage(resultStatus.getValue());
            return judgeInfoResponse;
        }
        for (int i = 0; i < outputList.size(); i++) {
            String output = outputList.get(i);
            String judgeCaseOutput = judgeCaseList.get(i).getOutput();
            //预期输出不相等
            if (!judgeCaseOutput.equals(output)) {
                resultStatus = JudgeInfoMessageEnum.WRONG_ANSWER;
                judgeInfoResponse.setMessage(resultStatus.getValue());
                return judgeInfoResponse;
            }
        }

        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        Long memoryLimit = judgeConfig.getMemoryLimit();
        Long timeLimit = judgeConfig.getTimeLimit();
        if (memoryLimit < memory) {
            resultStatus = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfoResponse.setMessage(resultStatus.getValue());
            return judgeInfoResponse;
        }
        if (timeLimit < time) {
            resultStatus = JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED;
            judgeInfoResponse.setMessage(resultStatus.getValue());
            return judgeInfoResponse;
        }

        judgeInfoResponse.setMessage(resultStatus.getValue());
        return judgeInfoResponse;
    }
}
